<template>
  <div>
    <StepProgress :step-index="1"/>
    <div>
      <el-form :model="appForm" :rules="appRules" status-icon ref="appForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="app id" prop="appId">
          <el-input type="text" v-model="appForm.appId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="app secret" prop="appSecret">
          <el-input type="password" v-model="appForm.appSecret" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('appForm')" :disabled="canSubmit">提交信息</el-button>
          <el-popover
              placement="top"
              :width="160"
              :visible="isVisible"
          >
            <p>此操作将会同步清空服务端的信息，确认删除？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="cancelClearAppInfo">取消</el-button>
              <el-button type="primary" size="mini" @click="resetForm('appForm')">确定</el-button>
            </div>
            <template #reference>
              <el-button type="danger" @click="isVisible = true">重置信息</el-button>
            </template>
          </el-popover>
        </el-form-item>
      </el-form>
      <button @click="config">点击</button>
      <div>
        <el-tag type="info">如需切换应用，重置信息重新输入即可。</el-tag> <br>
        <el-button type="primary" @click="goToNext">下一步</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import StepProgress from '@/components/StepProgress';
import Cookies from 'js-cookie';
import {clearInfo, getAppToken} from '@/api/auth/auth';
import {httpClient} from '@/utils/request';
import lark from '@/config';

export default {
  name: 'appInfo',
  components: {StepProgress},
  data() {
    const doGetAppInfo = this.$utils.getDebounceCallbackFn(async () => {
      // 1、提交验证成功后，把信息取hash存到cookie
      const {appId, appSecret} = this.appForm;
      this.$utils.genAppInfo(appId, appSecret);
      const content = await getAppToken(appId, appSecret);
      console.log(content);
      const {data} = content;
      if (data.code === 0) {
        this.$message.success('已成功上传应用信息！请勿重复操作');
        this.canSubmit = true;
        this.$utils.genAppInfo(appId, appSecret);
      } else {
        this.$message.error('未知原因');
      }
    }, 500);
    return {
      appForm: {
        appId: '',
        appSecret: '',
      },
      appRules: {
        appId: [
          {required: true, message: '请输入app id', trigger: 'blur'},
          {min: 20, max: 20, message: '输入的app id 不合法，请检查是否正确', trigger: 'blur'},
        ],
        appSecret: [
          {required: true, message: '请输入app secret', trigger: 'blur'},
          {min: 32, max: 32, message: '输入的app secret 不合法，请检查是否正确', trigger: 'blur'},
        ],
      },
      isVisible: false,
      canSubmit: false,
      doGetAppInfo,
    };
  },
  created() {
    const appBaseInfo = this.$store.getters.getAppInfo;
    this.appForm.appId = appBaseInfo.appId;
    this.appForm.appSecret = appBaseInfo.appSecret;
  },
  methods: {
    async config() {
      // 判断飞书环境
      await httpClient.get({
        url: lark.env.api.AUTH.V2_GET_APP_TOKEN,
      });
      const sdkContent = await httpClient.get({
        url: lark.env.api.AUTH.V2_JS_SDK,
        params: {
          url: lark.env.runtime.hashRouter ? window.location.href.split('#')[0] : window.location.href,
        },
      });
      console.log(sdkContent);
      const {appId, timestamp, signature, nonceStr} = sdkContent.data.data;
      console.log(appId, '---', timestamp, '---', signature, '----', nonceStr);
      window.h5sdk.config({
        appId, // 必填，应用ID
        timestamp, // 必填，生成签名的时间戳，ms级
        nonceStr, // 必填，生成签名的随机串
        signature, // 必填，签名
        jsApiList: [],
        onSuccess: (res) => {
          console.log('鉴权结果：', res);
          console.log(`config: success ${JSON.stringify(res)}`);
          tt.chooseChat({
            allowCreateGroup: false,
            multiSelect: true,
            selectType: 1,
            ignoreSelf: false,
            ignoreBot: false,
            confirmTitle: 'custom title',
            confirmDesc: 'custom desc',
            success(res) {
              console.log('choose chat success' + res.data);
            },
            fail(res) {
              console.log(`choose chat failed` + res);
            },
          });
        },
        onFailed: (res) => {
          console.log(`config: fail ${JSON.stringify(res)}`, 'test');
        },
      });
      window.h5sdk.error((err) => {
        console.error(JSON.stringify(err));
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.doGetAppInfo();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.appForm = {
        appId: '',
        appSecret: '',
      };
      this.$refs[formName].resetFields();
      this.$message.success('成功清空信息');
      this.isVisible = false;
      this.canSubmit = false;
      // 异步清空服务端信息
      clearInfo();
    },
    cancelClearAppInfo() {
      this.isVisible = false;
    },
    goToNext() {
      if (!this.canSubmit) {
        this.$message.warning('必须先确认信息才能进行下一步！');
        return;
      }
      Cookies.remove('uuid');
      // TODO 应用身份和用户身份分开搞
      this.$router.push({
        path: '/docs/docList',
        query: {
          type: 'app',
        },
      });
    },
  },
};
</script>

<style scoped>

</style>
